package org.oslims.server.dao.hbm;

import java.util.List;

import org.hibernate.Query;
import org.oslims.domain.AbstractSample;
import org.oslims.server.dao.AbstractSampleDao;

public class HbmAbstractSampleDao extends HbmGenericDao<AbstractSample, Long> implements AbstractSampleDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<AbstractSample> findByRequestCode(String code) {
		return this.getSession().createQuery("select distinct s from AbstractSample s join fetch s.requests as r where r.code = :code order by s.code desc")
				.setString("code", code).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AbstractSample> searchByProperties(String sampleCode, String description, String origin, String requestCode, String sampleType, String storagePlace) {

		Query q = this.getSession().createQuery(
				"select distinct s from AbstractSample s left join fetch s.requests as r where r.code like :requestCode and s.sampleType.name like :sampleType "
						+ "and s.code like :sampleCode "
						+ "and s.description like :description and s.origin like :origin and (s.storagePlace like :storagePlace or s.storagePlace is null) ");

		q.setString("requestCode", requestCode + "%");
		q.setString("sampleType", sampleType + "%");
		q.setString("sampleCode", sampleCode + "%");
		q.setString("description", description + "%");
		q.setString("origin", origin + "%");
		q.setString("storagePlace", storagePlace + "%");

		return q.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AbstractSample> findByAnalysisAndState(Long analyisId, String state) {
		Query q = this.getSession()
				.createQuery("select distinct s from AbstractSample s left join s.analysisResults ar where ar.analysis.id = :analysisId And s.state like :state").setLong(
						"analysisId", analyisId);
		q.setString("state", state);
		return q.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AbstractSample> findReadyForAnalysisByRequestCode(String code) {
		return this
				.getSession()
				.createQuery(
						"select distinct s from AbstractSample s join fetch s.requests as r where r.code = :code and s.state != :stateSample and s.state != :stateMixture order by s.code desc")
				.setString("code", code).setString("stateSample", "Not Recieved").setString("stateMixture", "Not Prepared").list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getSampleStatesForRequest(String requestCode) {
		Query q = this.getSession().createQuery("select distinct s.state from AbstractSample join s.requests r where r.code = :requestCode)");
		q.setString("requestCode", requestCode);

		return q.list();
	}
}
